
import request from "../api/request.js"
export default {
	// 连接socket.io
	conenct(context, username) {
		let {
			state
		} = context
		// 服务器地址
		// state.socket = io.connect("http://www.yemengs.cn")
		state.socket = uni.connectSocket({
				url: "ws://124.223.106.35:9999/websocket/"+username,
				// url: "ws://localhost:9999/websocket/"+username,
				success(data) {
					console.log("websocket连接成功");
				},
			});
		//let socket = state.socket; 
		// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
		state.socket.onOpen((res) => {
			console.log("WebSocket连接正常打开中...！");
			// 注：只有连接正常打开中 ，才能正常收到消息
			state.socket.onMessage((res) => {
				var msg = JSON.parse(res.data)
				console.log(msg)
				msg = JSON.parse(msg.textMessage)
				if(this.getters.getChatHistoryItem(msg.fromUser)==null){
					//console.log(this.to)
					this.dispatch('addHistoryListItem', msg.fromUser);
				}
				console.log(msg)
				//这里首先需要区分 接受的数据是聊天数据 0   还是好友请求数据  1    还是来电  2
				
				if(msg.messageType == 0){
					if(msg.id == -1){
						//说明这是在不在线的时候收到的消息
						console.log("不在的消息")
						console.log(msg)
						var messageContent = {
							message:msg.messageContent,
							nickname:msg.nickname,
							profilePhoto:msg.profilePhoto,
							time:msg.sendTime,
							tip:1,
							types:msg.messageType,
							username:msg.username
						}
						msg.messageContent = messageContent
						//console.log(msg.fromUser)
						
						//msg.messageContent = JSON.parse(msg.messageContent)
					}
					// console.log(msg)
					var temp = {}
					console.log(msg)
					if(msg.chatType == 'private'){
						temp = {
							 msg: msg,
							msg_list:this.getters.getChatHistory(msg.fromUser)
						}
					}
					else if(msg.chatType == 'public'){
						temp = {
									msg: msg,
									msg_list:this.getters.getChatHistory("All")
						}
					}
					
					this.commit("updateChatMsg",temp)
					
					this.commit("changDialogueInfo",msg)
					
					this.commit("changNewMsgCount")
				}
				else if(msg.messageType == 1){
					console.log("有好友请求来拉！")
					this.commit("changeAcquire")
				}
				else{
					
				}
				
			});
		})

	},
	// 发送ws消息
	webSocketSend(state, msg) {
		let that = this
		that.state.socket.send({
			data: JSON.stringify(msg),
			fail: function(res){
				console.log("发送失败")
				that.state.sendMsgStatus = true
			},
			success: function(res){
				console.log("发送成功")
				//that.state.sendMsgStatus = false
			}
		})
	},
	// 发送好友请求
	sendDemand(context, id) {
		let {
			state
		} = context
		state.socket.emit("sendDemand", {
			id
		})
	},
	// 处理好友请求
	dealFriend(context, data) {
		let {
			state
		} = context
		state.socket.emit("deal", data)
	},
	// 获取用户信息
	async getUserInfo(context) {
		let {
			state
		} = context
		let result = await request({
			url: '/user/info/'+uni.getStorageSync("userInfo").username,
			method: 'GET'
		});
		console.log("调用了！")
		state.user = result[1].data.data;
		console.log(result[1].data)
	},
	// 获取通知
	async getNotice(context) {
		let {
			state
		} = context
		let res = await request({
			url: "/notify/notice",
			data: {
				token: uni.getStorageSync("token")
			}
		})
		let resData = res[1].data
		let sum = 0  //统计通知的数量
		if (resData.notify_list) {
			state.notification = resData.notify_list
			state.notification.map(item => {
				if (item.unRead == false) {
					sum++
				}
			})
			this.commit("changeNotifySum",sum)
		} else {
			state.notification = []
			this.commit("changeNotifySum",sum)
		}
	},
	// 获取聊天记录
	async getChatHistory(context, data) {
		let {
			state
		} = context
		let res = await request({
			url: "/chat/history",
			data: {
				token: uni.getStorageSync("token"),
				id: data.id,
				type: data.type,
				page:data.page,
				limit:data.limit
			}
		})
		let result = res[1].data
		let msg_list =[]
		if(data.page == 1){ //加载第一页聊天记录时的操作
			msg_list = result.chats.msg_list
		}else{ //加载更多聊天记录时的操作
			msg_list = state.chatHistory.msg_list
			msg_list.unshift(...result.chats.msg_list)
			this.commit("changeIsLoading")
		}
		let time = null     //当前信息的发送时间
		let current = null  //前一条信息的发送时间
		let distant = null  //时间差
		// 遍历更改时间，当两条信息发送的时间间隔不超过指定时间时则将时间修改为‘’
		for (var i = 0; i < msg_list.length; i++) {
			if (i == msg_list.length - 1) {
				time = new Date(msg_list[i].date).getTime()
				current = new Date().getTime()
				distant = (current - time) / 1000 / 60
			} else {
				time = new Date(msg_list[i].date).getTime()
				current = new Date(msg_list[i + 1].date).getTime()
				distant = (current - time) / 1000 / 60
			}
			distant >= 10 ? "" : msg_list[i].date = ""
		}
		result.chats.msg_list = msg_list
		this.commit("changeChatHistory",result.chats)
		if(state.chatType=="private"){
			this.commit("changeChatName",result.name)
		}
		state.chatCount = result.count
	},
	// 获取聊天列表
	async getDialogue(context,username) {
		let {
			state
		} = context
		let res = await request({
			//url: '/user/friend/'+this.userInfo.username,
			url: '/recent?username='+username,
			method: 'GET'
		});
		for(var i = 0;i<res[1].data.data.length;i++){
			state.dialogueList.push(res[1].data.data[i])
		}
		// // 统计所有新信息的数量
		// let sum = 0
		// for(let i= 0;i<state.dialogueList.length;i++){
		// 	let item = state.dialogueList[i]
		// 	if(item.username == state.chatId){// 当天聊天页面的新信息的数量
		// 		state.newMsgCount = item.tip
		// 	}
		// 	sum = sum + item.unRead
		// }
		// this.commit("changeDialogueUnRead",sum)
	},
	// 获取好友请求数量
	async getAcquire(context) {
		let {
			state
		} = context
		let res = await request({
			url: '/friend/acquire',
			data: {
				token: uni.getStorageSync('token'),
				type: 'number'
			}
		});
		//this.commit("changeAcquire",res[1].data.applyList.length)
	},
	// 获取好友列表
	async getFriends(context) {
		let {
			state
		} = context
		let res = await request({
			url: '/user/friend/'+state.user.username
		});
		let result = res[1].data;
		//console.log(result.data)
		state.friends = result.data;
		state.friend_list = result.data
		state.total = result.data.length;
	},
	// 获取群组列表
	async getGroupList(context) {
		let {
			state
		} = context
		let res = await request({
			url: '/group/list',
			data: {
				token: uni.getStorageSync('token')
			}
		})
		state.groupList = res[1].data
	},
	// 获取群详情
	async getInfo(context, id) {
		let {
			state
		} = context
		let res = await request({
			url: '/group/info',
			data: {
				id,
				token: uni.getStorageSync('token')
			}
		});
		this.commit("changeGroupInfo",res[1].data)
		// state.groupInfo = res[1].data.group;
		// this.commit("changeChatName",res[1].data.group.name)
		// state.g_nickName = res[1].data.nickName;
	},
	// 获取新动态通知表
	async getDyNotify(context){
		let {
			state
		} = context
		let res = await request({
			url: '/dynamic/notify/get',
			data: {
				token: uni.getStorageSync('token')
			}
		});
		this.commit("changeDyNotify",res[1].data)
	},
	// 获取评论通知
	async getComNotify(context){
		let {
			state
		} = context
		state.count = 0
		let res = await request({
			url:"/comment/notify",
			data:{
				token: uni.getStorageSync('token'),
			}
		})
		this.commit("changeComNotify",res[1].data)
	},
	// 记录访客
	async recordVisitor(context,id){
		let {
			state
		} = context
		let res = await request({
			url:"/visitor/record",
			data:{
				id,
				token:uni.getStorageSync("token")
			},
			method:"POST"
		})
	},
	// 获取访客
	async acquireVisitors(context){
		let {
			state
		} = context
		if(state.visi_page==1){ //重置visitors
			this.commit("changeVisitors",[])
		}
		let res = await request({
			url:"/visitor/acquire",
			data:{
				token:uni.getStorageSync("token"),
				page:state.visi_page++,
				limit:state.visi_limit
			}
		})
		res = res[1].data
		state.visi_count = res.count
		state.visitors.push(...res.visitors) 
		this.commit("changeNewVisitorSum",res.newVisitor)
	},
	// 更新新访客数量
	async updateVisitor(context){
		let res = await request({
			url:"/visitor/update",
			data:{
				token:uni.getStorageSync("token"),
			},
			method:"POST"
		})
		this.dispatch("acquireVisitors")
	},
	// 获取留言通知表
	async obtainMessNotify(context){
		let {state} = context
		let res = await request({
			url:"/message/notify/obtain",
			data:{
				token:uni.getStorageSync("token"),
			}
		})
		state.messNotify = res[1].data.messNotify
		this.commit("changeMessageSum",res[1].data.count)
	},
	// 更新未读留言通知表
	async updateMessNotify(context){
		let {state} = context
		let res = await request({
			url:"/message/notify/update",
			data:{
				token:uni.getStorageSync("token"),
			},
			method:"POST"
		}) 
		if(res[1].data.status){
			this.dispatch("obtainMessNotify")
		}
	},
	
	
	//我的
	addHistoryListItem(context,username){
		let {state} = context
		//console.log("创建了！2",username)
		let newItem = {
			chatId:username,
			msg_list:[]
		}
		//console.log("创建了！3")
		state.chatHistory.push(newItem)
		//console.log("创建了！4")
		//console.log(state.chatHistory)
	}
}
